'''
Created on Nov 8, 2009

@author: Nick Verbeck
'''

from PyQt4 import QtGui
from PyQt4 import QtCore
from ui_MainWindow import Ui_GSync
import sys
import facebook
import facebookThread
import facebookLoggedIn

class MainWindow(QtGui.QMainWindow, Ui_GSync):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.setupUi(self)
        
        self.apiKey = '0282a8c286f42303b905e8e8ff8662aa'
        self.secretKey = '6348823ca477137748f29ac487e1c813'
        
        self.facebook = facebook.Facebook(self.apiKey, self.secretKey)
        self._facebookLoggedIn = False
        
        self.connect(self.btnRefreshFacebook, QtCore.SIGNAL("clicked()"), self._refreshFacebook)
        
        self._fbLoginThread = None
        self._fbFriendsThread = None
        self.fbLoggedInDialog = facebookLoggedIn.FacebookLoggedIn()
        self._fbFriends = None
        
        self._fbStatus = ''
        self._gStatus = ''
        
    def _refreshFacebook(self):
        self._fbStatus = 'Refreshing Facebook Contacts'
        self._updateStatus()
        
        if self._facebookLoggedIn:
            self._getFacebookFriends()
        else:
            self._fbStatus = 'Awaiting Login'
            self._updateStatus()
            
            self.fbLoggedInDialog.show()
            self._fbLoginThread = facebookThread.FacebookLoginThread(self.facebook, self.fbLoggedInDialog)
            self._fbLoginThread.start()
            self.connect(self._fbLoginThread, QtCore.SIGNAL("loggedIn"), self._loggedIntoFacebook)
            
    def _loggedIntoFacebook(self):
        self._fbStatus = 'Logged into Facebok'
        self._updateStatus()
        
        self._fbLoginThread = None
        self._getFacebookFriends()
            
    def _getFacebookFriends(self):
        self._fbStatus = 'Getting Friends'
        self._updateStatus()
        
        self._fbFriendsThread = facebookThread.FacebookFriendsThread(self.facebook)
        self._fbFriendsThread.start()
        self.connect(self._fbFriendsThread, QtCore.SIGNAL("gotFriends"), self._updateFacebookFriends)
        
    def _updateFacebookFriends(self, friends):
        self._fbStatus = 'Updating Facebook Contacts'
        self._updateStatus()
        
        self._fbFriendsThread = None
        self._fbFriends = friends
        
        self.cbFacebook.clear()
        for friend in self._fbFriends:
            self.cbFacebook.addItem(friend['name'])
        
        self._fbStatus = 'Done'
        self._updateStatus()
        
    def _updateStatus(self):
        self.statusBar().showMessage("Google Status: "+ self._gStatus +" - Facebook Status: "+ self._fbStatus)
        
if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.connect(app, QtCore.SIGNAL("lastWindowClosed()"), app, QtCore.SLOT("quit()"))
    sys.exit(app.exec_())